package cn.itcast.bos.web.action.base;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.service.base.IFixedAreaService;
import cn.itcast.bos.web.action.common.BaseAction;
import cn.itcast.crm.domain.Customer;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Actions
@Scope("prototype")
public class FixedAreaAction extends BaseAction<FixedArea> {
    // 注入service
    @Autowired
    private IFixedAreaService fixedAreaService;

    // 添加定区
    @Action(value = "fixedArea_save", results = {
            @Result(name = "success", location = "./pages/base/fixed_area.html", type = "redirect") })
    public String saveFixedArea() {
        fixedAreaService.saveFixedArea(model);

        return SUCCESS;
    }

    // 定区有条件分页查询
    @Action(value = "fixedArea_pageQuery", results = { @Result(name = "success", type = "json") })
    public String pageQueryFixedArea() {

        Pageable pageable = new PageRequest(page - 1, rows);
        // 添加条件
        Specification<FixedArea> specification = new Specification<FixedArea>() {
            List<Predicate> list = new ArrayList<Predicate>();

            @Override
            public Predicate toPredicate(Root<FixedArea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                // 按照定区编码查询
                if (StringUtils.isNotBlank(model.getId())) {
                    Predicate p1 = cb.equal(root.get("id").as(String.class), model.getId());
                    list.add(p1);

                }
                // 按照所属单位查询
                if (StringUtils.isNotBlank(model.getCompany())) {
                    Predicate p2 = cb.like(root.get("company").as(String.class), "%" + model.getCompany() + "%");
                    list.add(p2);
                }
                // 按照分区查询

                return cb.and(list.toArray(new Predicate[0]));
            }
        };
        Page<FixedArea> firedAreas = fixedAreaService.pageQueryFixedArea(specification, pageable);
        pushPageDataToValueStack(firedAreas);
        return SUCCESS;
    }

    // 查询为关联客户
    @Action(value = "firedArea_findNoAssociationCustomers", results = { @Result(name = "success", type = "json") })
    public String findNoAssociationCustomers() {
        Collection<? extends Customer> collection =
                WebClient.create("http://localhost:9002/crm_management/services/customerService/associationCustomers")
                        .accept(MediaType.APPLICATION_JSON).getCollection(Customer.class);
        ActionContext.getContext().getValueStack().push(collection);
        return SUCCESS;
    }

    // 查询已经关联的客户
    @Action(value = "firedArea_findHasAssociationFixedAreaCustomers", results = {
            @Result(name = "success", type = "json") })
    public String findHasAssociationFixedAreaCustomers() {
        Collection<? extends Customer> collection = WebClient
                .create("http://localhost:9002/crm_management/services/customerService/hasAssociationFixedAreaCustomers/"
                        + model.getId())
                .accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).getCollection(Customer.class);
        ActionContext.getContext().getValueStack().push(collection);
        return SUCCESS;
    }

    // 关联客户
    // 属性驱动
    private String[] customerIds;

    public void setCustomerIds(String[] customerIds) {
        this.customerIds = customerIds;
    }

    @Action(value = "fixedArea_associationCustomersToFixedArea", results = {
            @Result(name = "success", type = "redirect", location = "./pages/base/fixed_area.html") })
    public String associationCustomersToFixedArea() {
        String customerIdStr = "";
        if (customerIds != null) {
            customerIdStr = StringUtils.join(customerIds, ",");
        }

        WebClient
                .create("http://localhost:9002/crm_management/services/customerService/associationCustomersToFixedArea?customerIdStr="
                        + customerIdStr + "&fixedAreaId=" + model.getId())
                .put(null);
        return SUCCESS;
    }

    // 关联快递员
    // 属性驱动
    private Integer courierId;
    private Integer takeTimeId;

    public void setCourierId(Integer courierId) {
        this.courierId = courierId;
    }

    public void setTakeTimeId(Integer takeTimeId) {
        this.takeTimeId = takeTimeId;
    }

    @Action(value = "fixedArea_associationCourierToFixedArea", results = {
            @Result(name = "success", type = "redirect", location = "./pages/base/fixed_area.html") })
    public String associationCourierToFixedArea() {
        fixedAreaService.associationCourierToFixedArea(model, takeTimeId, courierId);
        return SUCCESS;
    }
}
